﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace MusicAcademy
{
    public partial class frmStudents : Form
    {
        public int recordID = -1;

        public frmStudents()
        {
            InitializeComponent();
        }

        private bool isValid()
        {
            bool valid = true;
            if (txtFirstName.Text.Trim() == "")
                valid = Globals.SetError(txtFirstName);
            else
                Globals.SetValid(txtFirstName);

            if (txtLastName.Text.Trim() == "")
                valid = Globals.SetError(txtLastName);
            else
                Globals.SetValid(txtLastName);

            if (txtFather.Text.Trim() == "")
                valid = Globals.SetError(txtFather);
            else
                Globals.SetValid(txtFather);

            if (txtBirthDate.IsValidDate() == false)
                valid = Globals.SetError(txtBirthDate);
            else if (string.Compare(txtBirthDate.Text, Globals.Get10CharDate()) > 0)
                valid = Globals.SetError(txtBirthDate);
            else
                Globals.SetValid(txtBirthDate);

            if (txtShenasnameh.Text.Trim() == "")
                valid = Globals.SetError(txtShenasnameh);
            else
                Globals.SetValid(txtShenasnameh);

            if (txtNationalCode.Text.Length != 10)
                valid = Globals.SetError(txtNationalCode);
            else
                Globals.SetValid(txtNationalCode);

            if (txtMobile.Text.Trim() != "" && (txtMobile.Text.Trim().Length < 11 || (txtMobile.Text.Trim().Length >= 2 && txtMobile.Text.Trim().Substring(0, 2) != "09")))
                valid = Globals.SetError(txtMobile);
            else
                Globals.SetValid(txtMobile);

            if (txtPostalCode.Text.Length > 0 && txtPostalCode.Text.Length < 10)
                valid = Globals.SetError(txtPostalCode);
            else
                Globals.SetValid(txtPostalCode);

            return valid;
        }

        private void frmStudents_Load(object sender, EventArgs e)
        {
            if (UserManager.HasAccess("frmStudents", "View") == false)
            {
                MessageBox.Show("شما اجازه ی دیدن این فرم را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.Close();
            }
            RefreshGrid();
        }

        private void RefreshGrid()
        {
            if (chkContainsSearch.Checked)
                this.personTableAdapter.Fill(this.musicAcademyDataSet.Person, 2, Program.academyID, txtFirstNameSearch.Text, txtLastNameSearch.Text, txtNationalCodeSearch.Text);
            else
                this.personTableAdapter.FillByStarting(this.musicAcademyDataSet.Person, 2, Program.academyID, txtFirstNameSearch.Text, txtLastNameSearch.Text, txtNationalCodeSearch.Text);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(Properties.Settings.Default.MusicAcademyConnectionString);
            SqlCommand com = new SqlCommand();
            SqlDataReader dreader;

            com.Connection = con;

            if (isValid() == false)
                return;

            if (recordID == -1)
            {
                if (UserManager.HasAccess("frmStudents", "Insert") == false)
                {
                    MessageBox.Show("شما اجازه ی اضافه کردن رکورد را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                com.CommandType = System.Data.CommandType.Text;
                com.CommandText = "INSERT INTO Person (firstName,lastName,father,shenasnameh,nationalCode,birthDate,address,postalCode,type,academyID,creator,createDate) VALUES (@firstName,@lastName,@father,@shenasnameh,@nationalCode,@birthDate,@address,@postalCode,@type,@academyID,@creator,@createDate); SELECT TOP 1 ID FROM Person WHERE type=2 ORDER BY ID DESC";
                com.Parameters.AddWithValue("@firstName", txtFirstName.Text);
                com.Parameters.AddWithValue("@lastName", txtLastName.Text);
                com.Parameters.AddWithValue("@father", txtFather.Text);
                com.Parameters.AddWithValue("@shenasnameh", txtShenasnameh.Text);
                com.Parameters.AddWithValue("@nationalCode", txtNationalCode.Text);
                com.Parameters.AddWithValue("@birthDate", txtBirthDate.Text);
                com.Parameters.AddWithValue("@address", txtAddress.Text);
                com.Parameters.AddWithValue("@postalCode", txtPostalCode.Text);
                com.Parameters.AddWithValue("@type", 2);
                com.Parameters.AddWithValue("@academyID", Program.academyID);
                com.Parameters.AddWithValue("@creator", Program.userID);
                com.Parameters.AddWithValue("@createDate", Globals.Get10CharDate());

                con.Open();
                dreader = com.ExecuteReader();
                dreader.Read();
                recordID = Convert.ToInt32(dreader["ID"]);
                con.Close();

                PhoneBook p = new PhoneBook();
                p.AddContact(txtFirstName.Text, txtLastName.Text, recordID);
                p.SaveDetail(recordID, "تلفن اصلی", txtTelephone.Text);
                p.SaveDetail(recordID, "موبایل اصلی", txtMobile.Text);
                p.CleanUpPersonContact(recordID);

                RefreshGrid();
            }
            else
            {
                if (UserManager.HasAccess("frmStudents", "Update") == false)
                {
                    MessageBox.Show("شما اجازه ی ویرایش کردن رکورد را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                com.CommandType = System.Data.CommandType.Text;
                com.CommandText = "UPDATE Person SET firstName=@firstName,lastName=@lastName,father=@father,shenasnameh=@shenasnameh,nationalCode=@nationalCode,birthDate=@birthDate, address=@address, postalCode=@postalCode, lastEditor=@lastEditor, editDate=@editDate WHERE ID=@ID";
                com.Parameters.AddWithValue("@ID", recordID);
                com.Parameters.AddWithValue("@firstName", txtFirstName.Text);
                com.Parameters.AddWithValue("@lastName", txtLastName.Text);
                com.Parameters.AddWithValue("@father", txtFather.Text);
                com.Parameters.AddWithValue("@shenasnameh", txtShenasnameh.Text);
                com.Parameters.AddWithValue("@nationalCode", txtNationalCode.Text);
                com.Parameters.AddWithValue("@birthDate", txtBirthDate.Text);
                com.Parameters.AddWithValue("@address", txtAddress.Text);
                com.Parameters.AddWithValue("@postalCode", txtPostalCode.Text);
                com.Parameters.AddWithValue("@lastEditor", Program.userID);
                com.Parameters.AddWithValue("@editDate", Globals.Get10CharDate());

                con.Open();
                com.ExecuteNonQuery();
                con.Close();

                PhoneBook p = new PhoneBook();
                p.EditContactByPersonID(recordID, txtFirstName.Text, txtLastName.Text);
                p.SaveDetail(recordID, "تلفن اصلی", txtTelephone.Text);
                p.SaveDetail(recordID, "موبایل اصلی", txtMobile.Text);
                p.CleanUpPersonContact(recordID);

                RefreshGrid();
            }
            MessageBox.Show("ذخیره شد", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            btnDelete.Enabled = true;
        }

        private void grdStudents_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
                return;

            Globals.SetValid(txtFirstName);
            Globals.SetValid(txtLastName);
            Globals.SetValid(txtFather);
            Globals.SetValid(txtBirthDate);
            Globals.SetValid(txtShenasnameh);
            Globals.SetValid(txtNationalCode);

            recordID = Convert.ToInt32(grdStudents.Rows[e.RowIndex].Cells["ID"].Value);
            txtFirstName.Text = grdStudents.Rows[e.RowIndex].Cells["FirstName"].Value.ToString();
            txtLastName.Text = grdStudents.Rows[e.RowIndex].Cells["LastName"].Value.ToString();
            txtFather.Text = grdStudents.Rows[e.RowIndex].Cells["Father"].Value.ToString();
            txtShenasnameh.Text = grdStudents.Rows[e.RowIndex].Cells["Shenasnameh"].Value.ToString();
            txtNationalCode.Text = grdStudents.Rows[e.RowIndex].Cells["NationalCode"].Value.ToString();
            txtBirthDate.Text = grdStudents.Rows[e.RowIndex].Cells["BirthDate"].Value.ToString();
            txtAddress.Text = grdStudents.Rows[e.RowIndex].Cells["address"].Value.ToString();
            txtPostalCode.Text = grdStudents.Rows[e.RowIndex].Cells["postalCode"].Value.ToString();

            PhoneBook p = new PhoneBook();
            txtTelephone.Text = p.LoadDetail(recordID, "تلفن اصلی");
            txtMobile.Text = p.LoadDetail(recordID, "موبایل اصلی");

            btnDelete.Enabled = true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            ClearForm();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(Properties.Settings.Default.MusicAcademyConnectionString);
            SqlCommand com = new SqlCommand();

            if (UserManager.HasAccess("frmStudents", "Delete") == false)
            {
                MessageBox.Show("شما اجازه ی حذف کردن رکورد را ندارید !", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (MessageBox.Show("آیا از حذف این رکورد اطمینان دارید ؟", "حذف", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                com.Connection = con;
                com.CommandType = CommandType.Text;

                com.CommandText = "DELETE FROM PersonFile WHERE personID=@ID; DELETE FROM Person WHERE ID=@ID; UPDATE Contact SET personID=NULL WHERE personID=@ID;";
                com.Parameters.AddWithValue("@ID", recordID);

                con.Open();
                com.ExecuteNonQuery();
                con.Close();
                ClearForm();
                RefreshGrid();

                MessageBox.Show("حذف شد", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void ClearForm()
        {
            recordID = -1;
            txtFirstName.Text = "";
            txtLastName.Text = "";
            txtFather.Text = "";
            txtShenasnameh.Text = "";
            txtNationalCode.Text = "";
            txtBirthDate.Text = "";
            txtAddress.Text = "";
            txtPostalCode.Text = "";
            txtTelephone.Text = "";
            txtMobile.Text = "";

            btnDelete.Enabled = false;

            Globals.SetValid(txtFirstName);
            Globals.SetValid(txtLastName);
            Globals.SetValid(txtFather);
            Globals.SetValid(txtBirthDate);
            Globals.SetValid(txtShenasnameh);
            Globals.SetValid(txtNationalCode);
        }

        private void txtFirstNameSearch_TextChanged(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void txtLastNameSearch_TextChanged(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void txtNationalCodeSearch_TextChanged(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void txtShenasnameh_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Globals.IsDigitOrCommand(e.KeyChar) == false)
                e.Handled = true;
        }

        private void txtNationalCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Globals.IsDigitOrCommand(e.KeyChar) == false)
                e.Handled = true;
        }

        private void txtNationalCodeSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Globals.IsDigitOrCommand(e.KeyChar) == false)
                e.Handled = true;
        }

        private void btnClearSearch_Click(object sender, EventArgs e)
        {
            txtFirstNameSearch.Text = "";
            txtLastNameSearch.Text = "";
            txtNationalCodeSearch.Text = "";
        }

        private void chkContainsSearch_CheckedChanged(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void txtTelephone_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Globals.IsDigitOrCommand(e.KeyChar) == false)
                e.Handled = true;
        }

        private void txtMobile_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Globals.IsDigitOrCommand(e.KeyChar) == false)
                e.Handled = true;
        }

        private void btnArchive_Click(object sender, EventArgs e)
        {
            frmPersonFiles p = new frmPersonFiles();
            p.PersonID = recordID;
            if (recordID != -1)
            {
                p.txtPerson.Text = txtFirstName.Text + " " + txtLastName.Text;
            }
            p.Show();
        }

        private void btnSessions_Click(object sender, EventArgs e)
        {
            frmSessions s = new frmSessions();
            s.StudentID = recordID;
            s.txtRegister.Text = "هنرجو " + txtFirstName.Text + " " + txtLastName.Text;
            s.txtStudentSearch.Text = txtFirstName.Text + " " + txtLastName.Text;
            s.ShowDialog();
        }
    }
}
